package com.enterpriseDigitalPlatform.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class JwtUtil {
    private JwtUtil() {
    }

    private static String applicationName;

    public static void setApplicationName(String name) {
        applicationName = name;
    }

    // 过期时间为60分钟 2 小时 修改为12小时
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    // 秘钥 32位随机字符串
    private static final String TOKEN_SECRET = "uXFC5yeTMaZVR667bVc8niAsxwHvtpCA";

    // 生成32位随机字符串密钥
    public static void main(String[] args) {
        int keyLen = 32;
        String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPRSTUVWXYZ";
        int len = str.length();
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyLen; i++) {
            int number = random.nextInt(len);
            sb.append(str.charAt(number));
        }
        System.out.println(sb);
    }


    /**
     * 创建token
     *
     * @return
     */
    public static String sign(Map<String, Object> claims) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        return JWT.create()
                .withClaim("data", claims)
                .withExpiresAt(date)
                .withIssuer(applicationName) // 签发者
                .sign(algorithm);
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public static Map<String, Object> verify(String token) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 验证 token
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(applicationName) // 签发者验证
                    .build();
            DecodedJWT decodedJWT = verifier.verify(token);
            // 获取载荷密文 没啥用
            // decodedJWT.getPayload()
            map.put("data", decodedJWT.getClaim("data").asMap());
            map.put("verify", true);
        } catch (IllegalArgumentException | JWTVerificationException e) {
            map.put("verify", false);
        }
        return map;
    }
}
